<template>
<div
    class="pm_bubble_menu_link"
    :editor="editor"
    v-show="isShow"
    >
        <!-- {{label}}:-->
        <div class="label">添加链接</div>
        <input class="pm_bubble_menu_input" v-model="linkTitle" placeholder="请输入"
            @input="changeErrorInfo($event,1)" />
        <div id="link_title_error" class="error" v-show="linkTitleError">请输入链接文本</div>
        <textarea class="pm_bubble_menu_input" v-model="linkUrl" placeholder="请输入链接，支持https:// http:// tg://"
            size="mini"
            :rules="validatorLinkUrl"
            :rows="3"
            @input="changeErrorInfo($event,2)"
            ></textarea>
        <div id="link_url_error" class="error" v-show="linkUrlError">url不能为空，且只允许使用以下协议：http:// 或 https:// 或 tg://</div>
        <div class="button_box">
            <button type="primary" size="mini" @click="changeLinkUrl($event,true)">确定</button>
            <button type="primary" size="mini" @click="deleteLinkUrl($event)">删除链接</button>
        </div>    
    </div>
</template>

<script>

// import {bm_link} from "../../../i18n.js"
import {getMarkAttributes} from "@tiptap/core";
export default {
    name:'bubble_menu_link',

    data() {
        return {
            // label:bm_link,
            linkUrl:"",
            linkTitle:"",
            from:0,
            to:0,
            isVisible: false,
            linkUrlError:false,
            linkTitleError:false,
            dialogHiddenCallback:()=>{},
            validatorLinkUrl:[{ validator:
                                function(rule, value, callback) {
                                    if (!/^http(s){0,1}:\/\/.*/.test(value)) {
                                        callback("请输入正确的url");
                                    } else {
                                        callback();
                                    }
                                },}],
            dbody:window.document.body,//只在移动端使用

        };
    },
    props: ["editor"],
    watch: {
    },
    mounted() {
        this.editor.toggleBubbleMenuLink = (callback) => {
            this.isVisible = !this.isVisible;
            this.dialogHiddenCallback = callback;
        };
    },
    beforeDestroy() {
        document.removeEventListener('click', this.handleDocumentClick);
    },
    beforeUnmount() {
    },
    computed: {
        isShow() {
            let {
                    linkTitle,
                    linkUrl,
                    from,
                    to
                } = this.getLinkinfo();

            this.linkUrl = linkUrl;
            this.linkTitle = linkTitle;
            this.from = from;
            this.to = to;
            this.linkUrlError = false;
            this.linkTitleError = false;
            if(this.isVisible){
                document.addEventListener('click', this.handleDocumentClick);
            }else{
                document.removeEventListener('click', this.handleDocumentClick);
            }
            return this.isVisible;
        },
    },
    // methods: {
    //     handleDocumentClick(e) {
    //         if (!this.$el.contains(e.target)) {
    //             this.isVisible = false;
    //         }
    //     },
    //     handleLinkClick() {
    //         this.editor.chain().focus().extendMarkRange('link').setLink({
    //             href: this.linkUrl,
    //             target: '_blank',
    //         }).run();
    //     }
    // },
    methods: {
        handleDocumentClick(event) {
            debugger
            if (!this.$el.contains(event.target)
                && !document.getElementById('zeditorlinkbtn').contains(event.target)
            ) {
                this.isVisible = false;
                this.dialogHiddenCallback();
            }
        },
        
        deleteLinkUrl(){
            this.editor.commands.setTextSelection({
                from:this.from,
                to:this.to,
            });
            this.editor.chain().focus().unsetLink().run();
            this.isVisible = false;
            this.dialogHiddenCallback();
        },
        changeErrorInfo(event,type){
            let matchResult = this.linkUrl.match(/^(http|https|tg)\:\/\/\S*$/);//简单写了一个
            if(!type||type==1){
                if(this.linkTitle.replace(/\s+/g,"").length>0){
                    this.linkTitleError = false;
                }else{
                    this.linkTitleError = true;
                }
            }
            
            if(!type||type==2){
                if(matchResult&&matchResult[0]){
                    this.linkUrl = matchResult[0];
                    this.linkUrlError = false;
                }else{
                    this.linkUrlError = true;
                }
            }
            if(!this.linkUrlError&&!this.linkTitleError){
                return true;
            }
        },
        changeLinkUrl(event,enterdown){
            let e = window.event || arguments[0];
            //^(http|https):\/\/([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}|([0-9]{1,3}\.){3}[0-9]{1,3})(:[0-9]{1,5})?(\/.*)?$  //这是chatgpt写的

            if(this.changeErrorInfo()){
                let isLink = this.editor.isActive('link');
                this.editor.commands.setTextSelection({
                    from:this.from,
                    to:this.to,
                });
                let nodes = [{type:'text',text:this.linkTitle,marks:[{type:'link',attrs:{href:this.linkUrl}}]}]
                if(!isLink){
                    nodes.push({type:'text',text:' '})
                }

                this.editor
                    .chain()
                    .insertContent(nodes)
                    .run();
                this.dialogHiddenCallback();
            }

            
            // const { from, to } = this.editor.state.selection;
            // const currentNode = this.editor.state.doc.nodeAt(from);
            // console.log('插入链接',currentNode,this.linkUrl);
            // if((!currentNode||currentNode.text == '')
            //     &&this.linkUrl!=''){
            //     this.editor
            //         .chain()
            //         .insertContentAt(from,[{type:'text',text:this.linkUrl,marks:[{type:'link',attrs:{href:this.linkUrl}}]},{type:'text',text:' '}])
            //         .run()
            // }else{
            //     this.editor
            //         .chain()
            //         .extendMarkRange('link')
            //         .updateAttributes('link', {
            //             href: this.linkUrl
            //         })
            //         .run()
            // }
            // if(enterdown){
            //     e.returnValue = false;
            //     return false;
            // }
        },
        //计算当前显示弹框事需要显示的内容
        getLinkinfo() {
            // 获取当前选区
            const selection = this.editor.state.selection;

            if(!this?.editor?.state?.selection?.$anchor?.pos){
                console.log('link出错了',);
                return {
                    linkTitle:'',
                    linkUrl:'',
                    from:0,
                    to:0
                };
            }
            // 获取当前光标所在的节点
            const $anchor = selection.$anchor;
            const currentPos = $anchor.pos;
            let from,to;
            let linkUrl,linkTitle;
            if(this.editor.isActive('link')){
                // 确定要扩展到的位置，这里假设扩展到整个文本节点的末尾
                from = currentPos - $anchor.textOffset;
                to = currentPos + $anchor.nodeAfter.nodeSize;

                // 更新选区
                // this.editor.commands.setTextSelection({
                //     from,
                //     to,
                // });
                linkUrl = '';
                let markAttributes = getMarkAttributes(this.editor.state, 'link');
                if(markAttributes.href){
                    linkUrl = markAttributes.href;
                }
                linkTitle = this.editor.state.doc.textBetween(from, to);
                return {
                    linkTitle,
                    linkUrl,
                    from,
                    to
                }
            }else{
                from = selection.from;
                to = selection.to;
                linkUrl = "";
                linkTitle = this.editor.state.doc.textBetween(from, to);
                console.log('不在link中',from,to,linkTitle);
                return {
                    linkTitle,
                    linkUrl,
                    from,
                    to
                }
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.pm_bubble_menu_link{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 9999;
    // border: 1px solid #ccc;
    padding: 10px;
    border-radius: 10px;
    background: linear-gradient(to bottom, #D5E5FD, #FBFDFF );
    padding: 20px;
    
    textarea,input{
        width: 100%;
        border: 0;
        padding: 10px;
        box-sizing: border-box;
        border-radius: 6px;
        margin-bottom: 10px;
        &:focus{
            outline: none;
        }
        &::placeholder {
            color: #ccc;
        }
    }
    textarea{
        height: 4rem;
    }
    .error{
        color: #d41010;
        margin-top: -6px;
        margin-bottom: 10px;
        font-size: 12px;
    }
    button{
        flex: 1;
        border: 0;
        padding: 10px;
        box-sizing: border-box;
        border-radius: 20px;
        background: linear-gradient(to right, #AAC7FF, #5C89F9 );
        color: #fff;
        cursor: pointer;
        margin: 0 10px;
    }
    .button_box{
        display: flex;
    }
    .label{
        font-size: 16px;
        color: #333333;
        margin-bottom: 5px;
    }
}
</style>
